
var app = getApp();
var Bmob = require('../../utils/bmob.js');

Page({
  data: {
    industryarr: [],
    industryindex: 0,
    checitems: [
      {
        "id": 0,
        "text": "WIFI",
        'checked': false
      },
      {
        "id": 1,
        "text": "支付宝",
        'checked': false
      },
      {
        "id": 2,
        "text": "微信",
        'checked': false
      },
      {
        "id": 3,
        "text": "POS机",
        'checked': false
      }
    ],
    logoImg: { url: '../../images/add.png'},
    uploadimgs: [],
    logoImgCheck: false,
    uploadimgsCheck: false,
    store_type: '',
    deleteImgs:[]//已经删除的文件列表
  },
  onLoad: function (options) {
    this.fetchData();

    if (app.isNotNullEmptyOrUndefined(options.businessId)) {
      let self = this;
      //设置当前店铺ID
      self.data.businessId = options.businessId;
      var businessImgquery = Bmob.Query('BusinessImg');
      businessImgquery.equalTo("business", '==', options.businessId);
      businessImgquery.include("business");
      businessImgquery.find().then(result => {
        var businessImgData = result;
        var industryindex = 0;
        for (var i = 0; i < this.data.industryarr.length; i++) {
          if (result[0].business.store_type == this.data.industryarr[i]) {
            industryindex = i;
          }
        }
        self.data.logoImgCheck = true;
        self.data.uploadimgsCheck = true;
        //设置当前店铺属性值以便保存
        self.setData({
          uploadimgs: businessImgData,
          businessData: result[0].business,
          logoImg: result[0].business.store_logo,
          industryindex: industryindex,
          store_type: this.data.industryarr[industryindex]
        });
      }).catch(error => {
        console.log(error);
        wx.hideLoading();
      });
    }

  },
  fetchData: function () {
    var self = this;
    var query = new Bmob.Query('PickerItem');
    query.equalTo('picker_type', '==', 'industry');
    query.find().then(res => {
      var industryarr = new Array();
      for (var i = 0; i < res.length; i++) {
        industryarr.push(res[i].picker_name);
      }
      self.setData({
        industryarr: industryarr
      });
    }).catch(error => {
      console.log(error);
      wx.hideLoading();
    });

  },
  bindPickerChange: function (e) { //下拉选择
    const eindex = e.detail.value;
    const name = e.currentTarget.dataset.pickername;
    // this.setData(Object.assign({},this.data,{name:eindex}))
    switch (name) {
      case 'industry':
        this.setData({
          industryindex: eindex
        });
        this.data.store_type = this.data.industryarr[eindex];
        break;
      case 'status':
        this.setData({
          statusindex: eindex
        })
        break;
      case 'job':
        this.setData({
          jobindex: eindex
        })
        break;
      default:
        return
    }
  },
  chooseImage: function (e) {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', e)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', e)
          }
        }
      }
    });
  },
  chooseWxImage: function (type, e) {
    let self = this;
    wx.showLoading({
      title: '上传中',
    })
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      count: parseInt(e.currentTarget.dataset.count),
      success: function (res) {
        let key = '';
        var file;
        for (let item of res.tempFilePaths) {
          var newDate = new Date();
          var newDateStr = newDate.getTime();
          var logoImgName = newDateStr + '.' + (/\.([^.]*)$/.exec(item)[1].toLowerCase());
          file = Bmob.File(logoImgName, item);
        }

        if (e.currentTarget.dataset.type == 'logo') {
          
          file.save().then(result => {
            self.data.logoImgCheck = true;
            result = JSON.parse(result);
            result.__type = 'File';
            self.setData({
              logoImg: result
            });
            wx.hideLoading();
          });

        }
        else if (e.currentTarget.dataset.type == 'store') {
          
          file.save().then(result => {
            self.data.uploadimgsCheck = true;
            var businessImgTempArray = new Array();
            for (var i = 0; i < result.length;i++){
              var businessImgTemp = {};
              businessImgTemp.img = JSON.parse(result[i]);
              businessImgTemp.img.__type = 'File';
              businessImgTempArray.push(businessImgTemp);
            }
            self.setData({
              uploadimgs: self.data.uploadimgs.concat(businessImgTempArray)
            });
            wx.hideLoading();
          });
        }
        
      }
    })
  },
  editImage: function () {
    this.setData({
      editable: !this.data.editable
    });
  },
  deleteImg: function (e) {
    let imgs = this.data.uploadimgs;
    this.data.deleteImgs.push(imgs[e.currentTarget.dataset.index]);
    imgs.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      uploadimgs: imgs
    });
  },
  onSelectTag: function (e) {
    const eid = e.currentTarget.dataset.id;
    const checitems = this.data.checitems;
    checitems[eid].checked = !checitems[eid].checked;
    this.setData({
      checitems: checitems
    });
  },
  applySubmit: function (e) {
    
    var self = this;

    //判断所有必填项是否填写
    if (!this.checkApplyForm(e)) {
      return false;
    }

    var formData = e.detail.value;
    var businessQuery = Bmob.Query('Business');

    let store_config = new Array();
    for (var i = 0; i < this.data.checitems.length; i++) {
      if (this.data.checitems[i].checked) {
        store_config.push(this.data.checitems[i].text);
      }
    }


    if (app.isNotNullEmptyOrUndefined(this.data.businessId)) {
      businessQuery.set('id', this.data.businessId)
    }
    let userPointer = {
      "__type": "Pointer",
      "className": "_User",
      "objectId": Bmob.User.current().objectId
    };
    businessQuery.set("user", userPointer);
    businessQuery.set("store_name", formData.store_name);
    businessQuery.set("store_type", this.data.store_type);
    businessQuery.set("store_logo", this.data.logoImg);
    businessQuery.set("store_introduce", formData.store_introduce);
    businessQuery.set("store_config", store_config);
    businessQuery.set("store_address", formData.store_address);
    businessQuery.set("business_hours", formData.business_hours);
    businessQuery.set("store_hot",0);

    wx.showLoading();
    businessQuery.save().then(businessObj => {
      self.data.businessId = businessObj.objectId || self.data.businessId;
      var businessImgArray = new Array();
      var businessImgQueryArray = new Array();
      //新增门店图片
      for (var i = 0; i < self.data.uploadimgs.length; i++) {
        if (app.isNotNullEmptyOrUndefined(self.data.uploadimgs[i].objectId)){
          continue;
        }
        var businessImgQuery = Bmob.Query('BusinessImg');
        var newDate = new Date();
        var newDateStr = newDate.getTime();
        var imgName = newDateStr + '_' + i + '.' + (/\.([^.]*)$/.exec(self.data.uploadimgs[i].img.url)[1].toLowerCase());
        var businessPointer = {
          "__type": "Pointer",
          "className": "Business",
          "objectId": self.data.businessId
        };
        businessImgQuery.set("business", businessPointer );
        businessImgQuery.set("img", self.data.uploadimgs[i].img);
        businessImgQueryArray.push(businessImgQuery);
      }
      //saveAll
      if (businessImgQueryArray.length > 0){
        Bmob.Query('BusinessImg').saveAll(businessImgQueryArray).then(result => {
          console.log(result);
          //提交成功后续操作
          self.afterApplySubmit();
        }).catch(error => {
          console.log(error);
          wx.showModal({
            title: '失败',
            content: '出错了，请稍后再试！',
            showCancel: false
          });
        });
      }
      else{
        self.afterApplySubmit();
      }
      

    }).catch(error => {
      console.log(error);
      wx.hideLoading();
    });
  },
  checkApplyForm: function (e) { //检验商家申请表单
    var self = this;
    var formData = e.detail.value;
    var checkMsg = '';
    if (!self.data.logoImgCheck) {
      checkMsg += '请选择logo\n';
    }
    if (app.isNullEmptyOrUndefined(formData.store_name)) {
      checkMsg += '请输入门店名称\n';
    }
    if (app.isNullEmptyOrUndefined(formData.store_address)) {
      checkMsg += '请输入门店地址\n';
    }
    let store_config = new Array();
    for (var i = 0; i < this.data.checitems.length; i++) {
      if (this.data.checitems[i].checked) {
        store_config.push(this.data.checitems[i].text);
      }
    }
    if (store_config.length == 0) {
      checkMsg += '请选择店内设施\n';
    }
    if (app.isNullEmptyOrUndefined(formData.business_hours)) {
      checkMsg += '请输入营业时间\n';
    }
    if (app.isNullEmptyOrUndefined(formData.store_introduce)) {
      checkMsg += '请输入门店简介\n';
    }

    if (!self.data.uploadimgsCheck) {
      checkMsg += '请选择门店图片\n';
    }

    if (app.isNullEmptyOrUndefined(self.data.store_type)) {
      checkMsg += '请选择门店分类\n';
    }

    if (app.isNotNullEmptyOrUndefined(checkMsg)) {
      wx.showModal({
        title: '失败',
        content: checkMsg,
        showCancel: false
      });
      return false;
    }
    else {
      return true;
    }
  },
  afterApplySubmit:function(e){
    var self = this;
    wx.hideLoading();
    wx.showModal({
      title: '成功',
      content: '恭喜，保存成功！',
      showCancel: false,
      success: function () {
        wx.redirectTo({
          url: '../space/space?businessId=' + (self.data.businessId),
        });
      },
      complete: function(){
        //删除无效的图片
        for (var i = 0; i < self.data.deleteImgs.length; i++) {
          var delFile = Bmob.File();
          delFile.destroy([self.data.deleteImgs[i].img.url]);
          var businessImgDelQuery = Bmob.Query('BusinessImg');
          businessImgDelQuery.destroy(self.data.deleteImgs[i].objectId).then(res => {
            console.log(res);
          }).catch(err => {
            console.log(err);
          })
        }
      }
    });
  }
})
